package com.ljx.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Filter;
import com.ljx.config.DatasourceTypeEnum;
import com.ljx.config.SwitchDatasource;
import com.ljx.dao.StudentRepo;
import com.ljx.model.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;

/**
 * Company: 上海数惠系统技术有限公司
 * Department: 数据中心：研发二部
 * Date: 2021/04/11 11:55
 *
 * @Author: Ljxpa
 * Email: lujx@dist.com.cn
 * Desc:
 */
@Service
public class StudentServiceImpl {

	@Autowired
	private StudentRepo studentRepo;

	@SwitchDatasource(dataSource = DatasourceTypeEnum.READ)
	public Student findOne(Integer id) {
		return studentRepo.getOne(id);
	}

	@SwitchDatasource(dataSource = DatasourceTypeEnum.READ)
	public List<Student> getAll() {
		return studentRepo.findAll();
	}

	@SwitchDatasource(dataSource = DatasourceTypeEnum.WRITE)
	@Transactional(rollbackFor = Exception.class)
	public Student saveOne(Student student) {
		Student save = studentRepo.save(student);
		Random random = new Random();
		int i = random.nextInt(10);
		if ((i % 2) == 0) {
			throw new RuntimeException("运行异常!");
		}
		return save;
	}

	public List<Student> findManyWithCondition(Integer id) {
		return studentRepo.findAllByIdGreaterThan(id);
	}

	public List<Student> findManyBetween(Integer start, Integer end) {
		List<Student> allByIdGreaterThan = studentRepo.findAllByIdGreaterThan(start);
		List<Student> allByIdLessThan = studentRepo.findAllByIdLessThan(end);
		List<Student> filter = CollectionUtil.filter(allByIdGreaterThan, new Filter<Student>() {
			@Override
			public boolean accept(Student student) {
				return allByIdLessThan.contains(student);
			}
		});
		return filter;
	}
}
